package bysj.controller.basic;

import bysj.domain.StudentClass;
import bysj.service.StudentClassService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
@Slf4j
@WebServlet("/studentClass.ctl")
public class StudentClassController {
    /**
     * GET, http://localhost:8080/school.ctl?id=1, 查询id=1的学院
     * GET, http://localhost:8080/school.ctl, 查询所有的学院
     * 把一个或所有学院对象响应到前端
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */

    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
            throws ServletException, IOException {
        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();
        //设置响应字符编码为UTF-8
       //  response.setContentType("application/json;charset=UTF-8");
        //将request body转换为JSON字串
        String req_jsonStr = util.JSONUtil.getJSON(request);
        //将request body解析为JSONObject对象
        JSONObject req_jsonObj = JSON.parseObject(req_jsonStr);
        //如果请求body为空
        if (req_jsonObj == null) {
            respMessage_jsonObj.put("message","未收到请求信息！");
            response.getWriter().println(respMessage_jsonObj);
            return;
        }
        //从JSONObject对象中读取键“id”的值（Java Object对象），req_jsonObj可能是{"id":1}
        Object id_obj = req_jsonObj.get("id");
        try {
            //如果id_Obj != null, 说明请求数据有id键，是请求某个教师对象
            if (id_obj != null) {
                int id_int = Integer.parseInt(id_obj.toString());
                responseStudentClass(id_int, response);
                log.info("id="+id_int);
            } else {//请求中包含条件和分页信息，需要响应多个教师对象
                    //读取分页信息，形成分页对象
                    //从JSONObject对象中读取 “pagination” 键对应的值(JSONObject对象)
                    util.Pagination pagination = util.ControllerHelper.getPagination(req_jsonObj);
                    //从请求JSONObject对象中读取键“conditionList”对应的值(描述查询条件的JSONArray对象)
                    List<util.Condition> conditionList = util.ControllerHelper.getConditions(req_jsonObj);
                    //响应多个学院信息，其中conditionList, pagination两个对象引用为空是可能的
                    this.responseStudentClasses(response, pagination, conditionList);
            }
        } catch (SQLException e) {
            respMessage_jsonObj.put("message", "数据库操作异常");
            //响应respMessage_jsonObj到前端
            response.getWriter().println(respMessage_jsonObj);
            //打印异常栈，方便调试（要用log4j代替）
            log.error("数据库操作异常:"+e);
        } catch (Exception e) {
            respMessage_jsonObj.put("message", "网络异常");
            //响应respMessage_jsonObj到前端
            response.getWriter().println(respMessage_jsonObj);
            //打印异常栈，方便调试（要用log4j代替）
            log.error("网络异常:"+e);
        }
    }
    //响应一个学院对象
    private void responseStudentClass(int id, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        //根据id查找学院
        StudentClass studentClass =
                StudentClassService.getInstance().find(id);
        String studentClass_json = JSON.toJSONString(studentClass);
        //响应school_json到前端
        response.getWriter().println(studentClass_json);
    }
    //响应所有学院对象
    private void responseStudentClasses(HttpServletResponse response, util.Pagination pagination, List<util.Condition> conditionList)
            throws ServletException, IOException, SQLException {
        //获得满足条件的所有院系
        Collection<StudentClass> studentClasses = StudentClassService.getInstance().findAll(conditionList,pagination);
        String studentClass_json = JSON.toJSONString(studentClasses, SerializerFeature.DisableCircularReferenceDetect);
        JSONObject response_json = new JSONObject();
        response_json.put("totalNum" ,pagination.getTotalNum());
        response_json.put("data",studentClass_json);
        //响应department_json 到前端
        response.getWriter().println(response_json);
    }

    //得到一个Logger对象，**.class是将要加入日志的类加进入
    //private final Logger logger = Logger.getLogger(StudentClassController.class);
}
